<template>
  <div>
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/ManageHome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      <el-breadcrumb-item>文创商品信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!--    功能区-->
        <div style="margin: 10px 0">
          <!--    搜索区-->
          <div style="margin: 10px 0;">
            <span style="font-weight:700; margin-right: 14px; font-size: 15px;">商品名称</span>
            <el-input v-model="searchName" clearable placeholder="请输入商品名称" prefix-icon="el-icon-search"
              style="margin-left:5px;width: 150px" size="small"/>
            <span style="font-weight:700; margin-left:10px; margin-right: 14px; font-size: 15px;">关键词</span>
            <el-input v-model="searchKeyWord" clearable placeholder="请输入关键词" prefix-icon="el-icon-search"
              style="margin-left:5px;width:150px" size="small"/>

            <span style="font-weight:700; margin-left: 10px; margin-right: 14px; font-size: 15px;">价格区间</span>
            <el-input v-model="topPrice" clearable placeholder="价格上界" prefix-icon="el-icon-search"
              style="margin-left:5px;width: 100px" size="small"/>
            <span> ~</span>
            <el-input v-model="bottomPrice" clearable placeholder="价格下界" prefix-icon="el-icon-search"
              style="margin-left:5px;width: 100px" size="small"/>

            <el-button icon="el-icon-search" @click="load"
              style="background-color: #143371;margin-left:10px; color: aliceblue;margin-left: 10px; margin-right: 14px;" size="small">搜索</el-button>
            <el-button icon="el-icon-refresh-left" style="margin-left:10px;background-color: #143371; color: aliceblue;margin-left: 10px; margin-right: 14px;"
              @click="reset" size="small">重置</el-button>

              
              <download-excel style="display: inline;"
                class="export-excel-wrapper"
                :data="tableData"
                :fields="json_fields"
                type="xls"
                worksheet="My Worksheet"
                name="商品信息"
    >
      <el-button style="background-color: #143371; color: aliceblue;"
      size="small"      >导出</el-button>
    </download-excel>
            

            <div style="float: right">

              <el-tooltip content="添加商品" placement="top">

                <el-button style="background-color: #143371; color: aliceblue;width: 40px;margin-left: 10px; margin-right: 14px;" icon="el-icon-plus"
                  @click="add" size="small"></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
        <!--    表格-->
        <el-table v-loading="loading" :data="tableData" max-height="1000" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="商品名称">
                  <span>{{ props.row.goodsName }}</span>
                </el-form-item>
                <el-form-item label="商品概要">
                  <p>{{ props.row.goodsDesc }}</p>
                </el-form-item>
                <el-form-item label="商品封面">
                  <img :src="props.row.goodsPic" alt="" style="width: 180px; height: 150px;">
                </el-form-item>
                <el-form-item label="更多图片">
                  <div style="display: flex;">
                    <img :src="item" alt="" v-for="(item, index) in props.row.imgs" :key="index"
                      style="width: 180px; height: 150px;">
                  </div>
                </el-form-item>


              </el-form>
            </template>
          </el-table-column>


          <el-table-column label="#" type="index" />
          <el-table-column label="编号" prop="goodsId" sortable width="140px" />
          <el-table-column label="名称" prop="goodsName" width="180px" />
          <el-table-column label="概要" prop="goodsDesc" width="180px">
          </el-table-column>
          <el-table-column label="类型" prop="type" width="150px" />
          <el-table-column label="原价" prop="goodsPrice" sortable width="120px" />
          <el-table-column label="现价" prop="goodsOriginPrice" sortable width="120px" />


          <!--      操作栏-->
          <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div style="margin: 10px 0">
          <el-pagination :currentPage="currentPage" :page-size="pageSize" :page-sizes="[10, 20]" :total="total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
        </div>
        <div>
          <!--      弹窗-->
          <el-dialog :visible.sync="dialogVisible" title="操作" width="50%" @close="cancel" top="30px">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">

              <el-form-item label="名称" prop="goodsName">
                <el-input v-model="form.goodsName" style="width: 80%" placeholder="商品的名字"></el-input>
              </el-form-item>

              <el-form-item label="概述" prop="goodsDesc">
                <el-input v-model="form.goodsDesc" style="width: 80%" placeholder="用一句话描述它"></el-input>
              </el-form-item>

              <el-form-item label="类型" prop="type">
                <el-input v-model="form.type" style="width: 80%" placeholder="在此输入类型"></el-input>
              </el-form-item>

              <el-form-item label="现价" prop="goodsPrice">
                <el-input v-model.number="form.goodsPrice" style="width: 80%" placeholder="商品当前价格"></el-input>
              </el-form-item>

              <el-form-item label="原价" prop="goodsOriginPrice">
                <el-input v-model="form.goodsOriginPrice" style="width: 80%" placeholder="商品原先价格"></el-input>
              </el-form-item>

              <el-form-item label="封面图" prop="goodsPic">
                <el-upload action="" list-type="picture-card" :limit="1" :on-preview="handlePictureCoverPreview"
                  :on-remove="handleCoverRemove" accept=".jpg,.png" :on-exceed="handleExceed" :file-list="cover_list"
                  :http-request="UploadCover">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="CoverdialogVisible">
                  <img width="100%" :src="CoverdialogImageUrl" alt="">
                </el-dialog>

              </el-form-item>
              <el-form-item label="商品图片(最多9张)" prop="imgs">
                <el-upload action="" list-type="picture-card" :limit="9" :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove" accept=".jpg,.png" :on-exceed="handleNineExceed" :auto-upload="true"
                  :file-list="more_list" :http-request="UploadMore" multiple>
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="MoredialogVisible">
                  <img width="100%" :src="MoredialogImageUrl" alt="">
                </el-dialog>

              </el-form-item>



            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
        
      </div>
    </el-card>
  </div>
</template>
<script>
import request from '@/utils/request'
export default {
  name: "SceneryInfo",
  data() {
    // 手机号验证
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    // const fieldName = ["商品ID", "商品图片", "商品品名", "商品描述", "商品类型", "商品现价", "商品原价"];
    //     const filterVal = ["goodsId", "goodsPic", "goodsName", "goodsDesc", "type", "goodsPrice", "goodsOriginPrice"];
    return {
      json_fields:{
        商品ID:'goodsId',
        商品名:'goodsName',
        商品描述:'goodsDesc',
        商品类型:'type',
        商品现价:"goodsPrice",
        商品原价:'goodsOriginPrice',
      },
      loading: true,
      editJudge: true,
      judge: false,
      dialogVisible: false,
      searchName: "",
      searchKeyWord: "",
      topPrice: 0,
      bottomPrice: 99999,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogloading: false,
      cover_list: [],
      more_list: [],
      CoverdialogImageUrl: '',
      CoverdialogVisible: false,
      MoredialogImageUrl: '',
      MoredialogVisible: false,
      coverImageUrl: '',
      moreImageUrl: [],

      tableData: [
        {
          goodsId: 1,
          goodsName: '好的东西',
          goodsDesc: '好东西',
          type: 1,
          goodsPrice: 1020,
          goodsOriginPrice: 5000,
          goodsPic: [],
          scStatus: true,
          imgs: [],
        }
      ],
      form: {

        goodsId: 1,
        goodsName: '好的东西',
        goodsDesc: 'haoekeai',
        type: 1,
        goodsPrice: 1020,
        goodsOriginPrice: 5000,
        goodsPic: '',
        scStatus: true,
        imgs: '',

      },
      rules: {
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^.+$/.test(value) == false) {
                callback(new Error("请输入内容"));
              } else {
                //校验通过
                callback();
              }
            }, trigger: 'blur'
          }
        ],
        ///^.+$/
        goodsPrice: [
          { required: true, message: "请输入商品现价", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^.+$/.test(value) == false) {
                callback(new Error("请输入内容"));
              } else {
                //校验通过
                callback();
              }
            }, trigger: 'blur'
          }
        ],
        goodsOriginPrice: [
          { required: true, message: "请输入商品原价", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^.+$/.test(value) == false) {
                callback(new Error("请输入内容"));
              } else {
                //校验通过
                callback();
              }
            }, trigger: 'blur'
          }

        ],

      },
      editDisplay: {
        display: "block",
      },
      display: {
        display: "none",
      },
    };
  },
  created() {
    this.reset();
    this.loading = true;
    setTimeout(() => {
      //设置延迟执行
      this.loading = false;
    }, 1000);
  },
  methods: {
    cancel() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.cover_list = []
      this.more_list = []
      this.CoverdialogImageUrl = ''
      this.MoredialogImageUrl = ''
      this.coverImageUrl = ''
      this.moreImageUrl = ''
    },
    UploadCover(data) {
      var formData = new FormData()
      formData.append('type', 'good')
      formData.append('file', data.file)
      this.dialogloading = true;
      console.log("图片文件", data)
      console.log("现在的图片", this.cover_list)
      request.post("/goods-info/upload", formData).then(res => {
        if (res.code === '1') {
          this.cover_list = []
          this.coverImageUrl = res.data,
            this.cover_list.push({ name: data.file.name, url: res.data })
          this.dialogloading = false;
        } else {
          this.dialogloading = false
          this.$message({
            type: 'error',
            message: '上传失败'
          })
        }

      })



    },
    UploadMore(data) {
      var formData = new FormData()
      formData.append('type', 'good')
      formData.append('file', data.file)
      this.dialogloading = true;
      console.log("上传详细图片", data)
      console.log("现在的图片", this.moreImageUrl)
      request.post("/goods-info/upload", formData).then(res => {
        if (res.code === '1') {
          // this.cover_list = []
        
          console.log("更多图片为：")
          console.log(this.moreImageUrl)
          this.more_list.push({ name: data.file.name, url: res.data })
          this.dialogloading = false;
        } else {
          this.dialogloading = false
          this.$message({
            type: 'error',
            message: '上传失败'
          })
        }

      })
    },
    handleRemove(file, fileList) {
      console.log("删除", file);
      this.more_list = this.more_list.filter(item => {
        return item.name != file.name
      })
    },
    handleCoverRemove(file, fileList) {
      console.log("删除", file);
      this.cover_list = []
    },
    handlePictureCoverPreview(file) {
      this.CoverdialogImageUrl = file.url;
      this.CoverdialogVisible = true;
    },
    handlePictureCardPreview(file) {
      this.MoredialogImageUrl = file.url
      this.MoredialogVisible = true
    },

    handleExceed() {
      this.$message.warning(`只允许上传一张图片`);
    },
    handleNineExceed() {
      this.$message.warning(`只允许上传9张图片`);
    },
    async load() {
      request.get("/goods-info/searchlist", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          searchName: this.searchName,
          searchKeyWord: this.searchKeyWord,
          topPrice: this.topPrice,
          bottomPrice: this.bottomPrice,
        },
      }).then((res) => {
        console.log("结果是：");
        console.log(res);
        this.tableData = res.data.goodsInfoList;
        this.total = res.data.total;
        this.loading = false;
        console.log(this.tableData);
      });
    },
    reset() {
      this.search = ''
      request.get("/goods-info/reset", {
        params: {
          pageNum: 1,
          pageSize: this.pageSize,
        },
      }).then((res) => {
        console.log(res);
        this.tableData = res.data.goodsInfoList;
        this.total = res.data.total;
        this.loading = false;
       
      
      });
    },
    handleDelete(index, row) {
      // 确认框确认是否要删除
      this.$confirm("确定要删除" + row.goodsName + "的信息吗?", "删除提示", {
        iconClass: "el-icon-question", //自定义图标样式
        confirmButtonText: "残忍删除", //确认按钮文字
        cancelButtonText: "取消删除", //取消按钮文字
        showClose: true, //是否显示右上角关闭按钮
        type: "warning", //提示类型  success/info/warning/error
      }).then(() => {  //选择确认按钮进入此方法
        var temp = { goodsId: row.goodsId }
        request.delete("/goods-info/delete", { params: temp }).then(res => {
          console.log(row.goodsId)
          if (res.code === "1") {
            this.$message({
              type: 'success',
              message: '删除成功',

            })
            this.reset();
          }
          else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })

      }).catch(() => { //选择取消按钮进入此方法
        //取消操作
        alert('取消')
      });
    },
    handleEdit(index, row) {
      this.judge = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form = JSON.parse(JSON.stringify(row));
        this.cover_list.push({name:"goods",url:this.form.goodsPic})
       
        this.form.goodsId = parseInt(this.form.goodsId)
        this.more_list = []
       for(var i =0;i<this.form.imgs.length;i++){
         this.more_list.push({name:'goods'+i,url:this.form.imgs[i]})
       }
        this.editDisplay = { display: "block" };
      });
    },
    save() {
      this.$refs.form.validate(vaild => {
        if (vaild) {
          if (this.judge) {
            //先表单验证，再放put请求
          
            this.form.goodsPic = this.cover_list[0].url
            this.form.imgs = []
            for(var i=0;i<this.more_list.length;i++){
              
              this.form.imgs.push(this.more_list[i].url)
             
            }
            request.put("/goods-info/update", this.form).then(res => {
              if (res.code === "1") {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.reset()
                this.more_list = []
                this.search = "",
                  this.dialogVisible = false
              }
              else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })


          }
          else {
            //发post请求
         
            this.form.goodsPic = this.cover_list[0].url
            this.form.imgs = []
           
            for(var i=0;i<this.more_list.length;i++){
              
              this.form.imgs.push(this.more_list[i].url)
             
            }
            request.post("/goods-info/addgoods", this.form).then(res => {
              if (res.code === "1") {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.load()
                this.search = "",
                this.dialogVisible = false
              }
              else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            })
          }
        }
      })
      this.load();
      this.cancel();

    },
   

    add() {
      this.dialogVisible = true;
      this.judge = false;
      this.form = {}
    },
    handleSizeChange(pageSize) {
      //改变每页个数
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      //改变页码
      this.currentPage = pageNum;
      this.load();
    },

  }


}
</script>
<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
  display: block;
}</style>